package top.laoshuzi.android.tts.core;

import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.speech.tts.TextToSpeech;
import top.laoshuzi.android.tts.ITtsService;
import top.laoshuzi.android.tts.core.exception.TtsException;

/**
 * Created by Mouse on 2017/5/3.
 */

public class TtsManager {

    public static final String TTS_SERVICE_NAME = "tts_service";

    private static TtsManager mTtsManager = null;

    private ITtsService ttsService = null;

    private TtsManager() {
        checkTtsServiceConnection();
    }

    private void createTtsService() {
        IBinder binder = ServiceManager.getService(TTS_SERVICE_NAME);
        ttsService = ITtsService.Stub.asInterface(binder);
    }

    private void checkTtsServiceConnection() throws TtsException {
        if (ttsService == null) {
//            throw new TtsException("TtsService is dead");
            createTtsService();
        }
    }

    public static TtsManager getInstance() {
        if (mTtsManager == null) {
            synchronized (TtsManager.class) {
                if (mTtsManager == null) {
                    mTtsManager = new TtsManager();
                }
            }
        }
        return mTtsManager;
    }

    public void speak(String text) throws TtsException {
        speak(text, TextToSpeech.QUEUE_FLUSH);
    }

    public void speak(String text, int mode) throws TtsException {

        if (text == null)
            return;

        try {
            checkTtsServiceConnection();
            ttsService.speak(text, mode);
        } catch (RemoteException e) {
            throw new TtsException("speak()", e);
        }
    }

    public void open() throws TtsException {
        try {
            checkTtsServiceConnection();
            ttsService.open();
        } catch (RemoteException e) {
            throw new TtsException("open()", e);
        }
    }

    public void shutdown() throws TtsException {
        try {
            checkTtsServiceConnection();
            ttsService.shutdown();
        } catch (RemoteException e) {
            throw new TtsException("shutdown()", e);
        }
    }


}
